<template>
  <div class="app-breadcrumb-wrapper">
    <el-breadcrumb class="app-breadcrumb" separator="/">
      <transition-group name="breadcrumb">
        <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
          <span
            v-if="item.redirect === 'noRedirect' || index === levelList.length - 1"
            class="no-redirect"
          >
            <el-icon v-if="item.meta.icon" class="breadcrumb-icon"><component :is="item.meta.icon" /></el-icon>
            {{ t(item.meta.title) }}
          </span>
          <a v-else @click.prevent="handleLink(item)" class="breadcrumb-link">
            <el-icon v-if="item.meta.icon" class="breadcrumb-icon"><component :is="item.meta.icon" /></el-icon>
            {{ t(item.meta.title) }}
          </a>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

const levelList = ref([])
const route = useRoute()
const router = useRouter()
const { t } = useI18n()

// 获取最后一个导航项
const lastItem = computed(() => {
  return levelList.value.length > 0 ? levelList.value[levelList.value.length - 1] : null
})

/**
 * 获取面包屑导航数据
 */
const getBreadcrumb = () => {
  // 只显示带有 meta.title 的路由项
  let matched = route.matched.filter(item => item.meta && item.meta.title)
  
  // 如果第一个路由不是首页，添加首页
  // const first = matched[0]
  // if (first && first.path !== '/dashboard') {
  //   matched = [
  //     {
  //       path: '/dashboard',
  //       meta: { title: 'menu.dashboard', icon: 'House' }
  //     },
  //     ...matched
  //   ]
  // }
  
  levelList.value = matched
}

/**
 * 处理面包屑导航链接点击
 * @param {Object} item 路由项
 */
const handleLink = item => {
  const { path, query } = item
  router.push({ path, query })
}

// 监听路由变化，更新面包屑导航
watch(
  () => route.path,
  () => {
    getBreadcrumb()
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.app-breadcrumb-wrapper {
  display: flex;
  padding: 12px 0;
}

.app-breadcrumb {
  display: flex;
  font-size: 13px;
  
  :deep(.el-breadcrumb__inner) {
    color: $textSecondary;
  }
  
  :deep(.el-breadcrumb__inner.is-link) {
    font-weight: normal;
  }
  
  :deep(.el-breadcrumb__separator) {
    color: #c0c4cc;
    margin: 0 6px;
  }
  
  .no-redirect {
    color: $textRegular;
    cursor: text;
  }
  
  .breadcrumb-link {
    color: $textSecondary;
    transition: color 0.2s;
    cursor: pointer;
    
    &:hover {
      color: $primaryColor;
    }
  }
  
  .breadcrumb-icon {
    margin-right: 4px;
    font-size: 14px;
    vertical-align: -0.15em;
  }
}

// 面包屑切换动画
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.3s ease;
}

.breadcrumb-enter-from,
.breadcrumb-leave-active {
  opacity: 0;
  transform: translateX(10px);
}

.breadcrumb-leave-active {
  position: absolute;
}
</style>